import { Controller, Post, Body, Get, Param, ParseIntPipe, UseGuards, Request, Delete, Patch, HttpException, HttpStatus } from '@nestjs/common';
import { UserService } from './user.service';
import { CreateUserDto } from './dto/create-user.dto';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';

@Controller('users')
export class UserController {
  constructor(private readonly userService: UserService) {}

  @Post('register')
  async register(@Body() createUserDto: CreateUserDto) {
    return this.userService.create(createUserDto);
  }
  
  @Post('init-admin')
  async initAdmin() {
    const adminExists = await this.userService.findByUsername('admin');
    if (adminExists) {
      return { message: '系统管理员已存在', username: 'admin' };
    }
    
    const adminUser = await this.userService.create({
      username: 'admin',
      password: 'admin123',
      level: 1
    });
    
    return { 
      message: '系统管理员创建成功', 
      username: adminUser.username,
      password: 'admin123'
    };
  }

  @UseGuards(JwtAuthGuard)
  @Get('profile')
  async getProfile(@Request() req) {
    const user = await this.userService.findById(req.user.userId);
    if (!user) {
      throw new Error('User not found');
    }
    return user;
  }
  
  @UseGuards(JwtAuthGuard)
  @Get()
  async findAll(@Request() req) {
    // 只有管理员可以查看所有用户
    const currentUser = await this.userService.findById(req.user.userId);
    if (!currentUser || currentUser.level > 2) {
      throw new HttpException('没有权限访问此资源', HttpStatus.FORBIDDEN);
    }
    
    return this.userService.findAll();
  }
  
  @UseGuards(JwtAuthGuard)
  @Post()
  async createUser(@Body() createUserDto: CreateUserDto, @Request() req) {
    // 只有管理员可以创建用户
    const currentUser = await this.userService.findById(req.user.userId);
    if (!currentUser || currentUser.level > 1) {
      throw new HttpException('没有权限创建用户', HttpStatus.FORBIDDEN);
    }
    
    // 检查用户名是否已存在
    const existingUser = await this.userService.findByUsername(createUserDto.username);
    if (existingUser) {
      throw new HttpException('用户名已存在', HttpStatus.BAD_REQUEST);
    }
    
    return this.userService.create(createUserDto);
  }
  
  @UseGuards(JwtAuthGuard)
  @Patch(':id')
  async updateUser(@Param('id', ParseIntPipe) id: number, @Body() updateData: any, @Request() req) {
    // 只有管理员可以更新用户
    const currentUser = await this.userService.findById(req.user.userId);
    if (!currentUser || currentUser.level > 1) {
      throw new HttpException('没有权限更新用户', HttpStatus.FORBIDDEN);
    }
    
    return this.userService.update(id, updateData);
  }
  
  @UseGuards(JwtAuthGuard)
  @Delete(':id')
  async removeUser(@Param('id', ParseIntPipe) id: number, @Request() req) {
    // 只有管理员可以删除用户
    const currentUser = await this.userService.findById(req.user.userId);
    if (!currentUser || currentUser.level > 1) {
      throw new HttpException('没有权限删除用户', HttpStatus.FORBIDDEN);
    }
    
    // 不能删除自己
    if (currentUser.id === id) {
      throw new HttpException('不能删除自己的账号', HttpStatus.BAD_REQUEST);
    }
    
    return this.userService.remove(id);
  }

  @UseGuards(JwtAuthGuard)
  @Get('admins/list')
  async getAdminsList(@Request() req) {
    const currentUser = await this.userService.findById(req.user.userId);
    if (!currentUser) {
      throw new HttpException('用户不存在', HttpStatus.NOT_FOUND);
    }
    
    // 返回所有管理员的基本信息（用于筛选下拉框）
    const admins = await this.userService.findAll();
    return admins.map(admin => ({
      id: admin.id,
      username: admin.username,
      level: admin.level
    }));
  }

  @Get(':id')
  async findOne(@Param('id', ParseIntPipe) id: number) {
    return this.userService.findById(id);
  }
}